/**
 * Created by alice on 2017/5/22 0022.
 */

var vlc_playlist = [];//存储播放列表数组
var now_playing = 0;//正在播放的编号
var timeline;//时间轴图片地址数组

function getVLC(name) {
    if (window.document[name]) {
        return window.document[name];
    }
    if (navigator.appName.indexOf("Microsoft Internet") == -1) {
        if (document.embeds && document.embeds[name])
            return document.embeds[name];
    }
    else {
        return document.getElementById(name);
    }
};

var vlc = getVLC("vlc");

//加载插件
if (navigator.appName.indexOf("Microsoft Internet") == -1) {
    onVLCPluginReady()
} else if (document.readyState == 'complete') {
    onVLCPluginReady();
} else {
    /* Explorer loads plugins asynchronously */
    document.onreadystatechange = function () {
        if (document.readyState == 'complete') {
            onVLCPluginReady();
        }
    }
}
var pro_bar = progress.init('#pro_bar', {});
pro_bar.pause = function () {
    //vlc.input.state：当前状态（空闲/关闭= 0，开幕= 1，缓冲= 2，打= 3，暂停= 4，停止= 5，错误= 6）
    if (vlc.input.state == 3) {
        vlc.playlist.togglePause();
    }
};
pro_bar.play = function () {
    if (vlc.input.state == 4) {
        vlc.playlist.togglePause();
        onPlaying();
    }
};
pro_bar.changeVolume = function (volume) {
    vlc.audio.volume = volume * 100;
};
pro_bar.changeCurrentTime = function (currentTime) {
    vlc.input.time = currentTime * 1000;
};
pro_bar.browserFullscreen = function () {
    vlc.video.toggleFullscreen();
};

//初始化播放列表并播放第一个
var init_playlist = function (num, temp_playlist) {
    vlc_playlist = temp_playlist || vlc_playlist;
    now_playing = num || 0;
    var options = [":vout-filter=deinterlace", ":deinterlace-mode=linear"];
    vlc.playlist.items.clear();
    $(vlc_playlist).each(function (index, elem) {
        vlc.playlist.add(elem.playUrl, "", options);
    });
    console.log('播放列表构建完毕', vlc_playlist);
    vlc.playlist.playItem(now_playing);
};
var play_video = function (num, time) {
    now_playing = num || 0;
    console.log('切换播放，获取video ：' + now_playing);
    vlc.playlist.playItem(now_playing);
    if (time) {
        vlc.input.time(time);
    }
}

function onPlaying() {
    var mediaLen = vlc.input.length;
    if (mediaLen > 0) {
        mediaLen = Math.floor(mediaLen / 1000);
        console.log('on_playing', mediaLen);
        pro_bar.loadeddata(mediaLen, vlc.audio.volume / 100);
        change_pro();
        timeline2(vlc_playlist[now_playing].uid, mediaLen);
    }
}

function onPause() {
    var play = $('.audioplayer-playpause').find('a');
    if (play.html() == 'Pause') {
        play.click();
    }
}

var change_pro = function () {
    var play = $('.audioplayer-playpause').find('a');
    console.log(play.html());
    if (play.html() == 'Play') {
        play.click();
    }
};
var timeline2 = function (uid, time) {
    if (time) {
        $.post(r.base_path + 'image/timeline2', {uid: uid, timeSize: time}, function (result) {
            if (result && result.code == 0) {
                timeline = result.data;
                console.log('获取时间轴图片地址成功',result.data);
                $(timeline).each(function (index, elem) {
                    elem = elem.replace('http://127.0.0.18080/usr/local/movies/images/timeline','/timeline')
                    timeline[index] =elem;
                });
                console.log('获取时间轴图片地址成功',timeline);
                pro_bar.loadImg(timeline);
            }
        }, 'json')
    }
};

// JS VLC API callbacks
function handleMediaPlayerMediaChanged() {
    console.log('播放编号：' + now_playing)
}

//更新正在播放的时间
function handle_MediaPlayerTimeChanged(time) {
    var mediaLen = vlc.input.length;
    if (mediaLen > 0) {
        pro_bar.timeupdate(time / 1000);
    }
}

function handle_MediaPlayerNothingSpecial() {
}

function handle_MediaPlayerOpening() {
}

function handle_MediaPlayerBuffering(val) {
}

function handle_MediaPlayerPlaying() {
    onPlaying();
}

function handle_MediaPlayerPaused() {
    onPause();
}

function handle_MediaPlayerStopped() {
}

function handle_MediaPlayerForward() {
}

function handle_MediaPlayerBackward() {
}

//视频播放置底触发，播放编号+1
function handle_MediaPlayerEndReached() {
    (++now_playing) >= vlc_playlist.length ? now_playing = 0 : ''
}

function handle_MediaPlayerEncounteredError() {
}

function handle_MediaPlayerPositionChanged(val) {
    // console.log('handle_MediaPlayerPositionChanged',val);
}

function handle_MediaPlayerSeekableChanged(val) {
    // console.log('handle_MediaPlayerSeekableChanged', val);
}

function handle_MediaPlayerPausableChanged(val) {
    // console.log('handle_MediaPlayerPausableChanged', val);
}

function handle_MediaPlayerTitleChanged(val) {
    // console.log('handle_MediaPlayerTitleChanged', val);
}

function handle_MediaPlayerLengthChanged(val) {
    console.log('handle_MediaPlayerLengthChanged', val);
}

// VLC Plugin
function onVLCPluginReady() {
    registerVLCEvent("MediaPlayerMediaChanged", handleMediaPlayerMediaChanged);
    registerVLCEvent("MediaPlayerNothingSpecial", handle_MediaPlayerNothingSpecial);
    registerVLCEvent("MediaPlayerOpening", handle_MediaPlayerOpening);
    registerVLCEvent("MediaPlayerBuffering", handle_MediaPlayerBuffering);
    registerVLCEvent("MediaPlayerPlaying", handle_MediaPlayerPlaying);
    registerVLCEvent("MediaPlayerPaused", handle_MediaPlayerPaused);
    registerVLCEvent("MediaPlayerStopped", handle_MediaPlayerStopped);
    registerVLCEvent("MediaPlayerForward", handle_MediaPlayerForward);
    registerVLCEvent("MediaPlayerBackward", handle_MediaPlayerBackward);
    registerVLCEvent("MediaPlayerEndReached", handle_MediaPlayerEndReached);
    registerVLCEvent("MediaPlayerEncounteredError", handle_MediaPlayerEncounteredError);
    registerVLCEvent("MediaPlayerTimeChanged", handle_MediaPlayerTimeChanged);
    registerVLCEvent("MediaPlayerPositionChanged", handle_MediaPlayerPositionChanged);
    registerVLCEvent("MediaPlayerSeekableChanged", handle_MediaPlayerSeekableChanged);
    registerVLCEvent("MediaPlayerPausableChanged", handle_MediaPlayerPausableChanged);
    registerVLCEvent("MediaPlayerTitleChanged", handle_MediaPlayerTitleChanged);
    registerVLCEvent("MediaPlayerLengthChanged", handle_MediaPlayerLengthChanged);
}

window.onbeforeunload = close;

function close() {
    unregisterVLCEvent("MediaPlayerMediaChanged", handleMediaPlayerMediaChanged);
    unregisterVLCEvent("MediaPlayerNothingSpecial", handle_MediaPlayerNothingSpecial);
    unregisterVLCEvent("MediaPlayerOpening", handle_MediaPlayerOpening);
    unregisterVLCEvent("MediaPlayerBuffering", handle_MediaPlayerBuffering);
    unregisterVLCEvent("MediaPlayerPlaying", handle_MediaPlayerPlaying);
    unregisterVLCEvent("MediaPlayerPaused", handle_MediaPlayerPaused);
    unregisterVLCEvent("MediaPlayerStopped", handle_MediaPlayerStopped);
    unregisterVLCEvent("MediaPlayerForward", handle_MediaPlayerForward);
    unregisterVLCEvent("MediaPlayerBackward", handle_MediaPlayerBackward);
    unregisterVLCEvent("MediaPlayerEndReached", handle_MediaPlayerEndReached);
    unregisterVLCEvent("MediaPlayerEncounteredError", handle_MediaPlayerEncounteredError);
    unregisterVLCEvent("MediaPlayerTimeChanged", handle_MediaPlayerTimeChanged);
    unregisterVLCEvent("MediaPlayerPositionChanged", handle_MediaPlayerPositionChanged);
    unregisterVLCEvent("MediaPlayerSeekableChanged", handle_MediaPlayerSeekableChanged);
    unregisterVLCEvent("MediaPlayerPausableChanged", handle_MediaPlayerPausableChanged);
    unregisterVLCEvent("MediaPlayerTitleChanged", handle_MediaPlayerTitleChanged);
    unregisterVLCEvent("MediaPlayerLengthChanged", handle_MediaPlayerLengthChanged);
}

function registerVLCEvent(event, handler) {
    if (vlc) {
        if (vlc.attachEvent) {
            // Microsoft
            vlc.attachEvent(event, handler);
        } else if (vlc.addEventListener) {
            // Mozilla: DOM level 2
            vlc.addEventListener(event, handler, true);
        } else {
            // DOM level 0
            eval("vlc.on" + event + " = handler");
        }
    }
}

function unregisterVLCEvent(event, handler) {
    if (vlc) {
        if (vlc.detachEvent) {
            // Microsoft
            vlc.detachEvent(event, handler);
        } else if (vlc.removeEventListener) {
            // Mozilla: DOM level 2
            vlc.removeEventListener(event, handler, true);
        } else {
            // DOM level 0
            eval("vlc.on" + event + " = null");
        }
    }
}
